import { api } from '../api/api';
import EventEmitter from './EventEmitter'; // 确保路径正确
import { myRequest } from './api';

export default class WebSocketService {
  constructor(url) {
    this.url = url;
    this.socketTask = null;
    this.maxReconnectAttempts = 10;
    this.reconnectInterval = 5000;
    this.isClosedByUser = false; // 标志位，用于区分用户主动关闭和被动关闭
    this.eventEmitter = new EventEmitter(); // 初始化 EventEmitter
  }

  connect() {
    if (this.isClosedByUser) {
      // 如果是用户主动关闭连接，不再尝试重连
      return;
    }

    console.log('尝试连接 WebSocket');
    this.socketTask = uni.connectSocket({
      url: this.url,
      success: () => {
        // 重置重连尝试次数只有在连接成功时进行
        this.reconnectAttempts = 0;
      },
      fail: (err) => {
        console.log('WebSocket连接失败:', err);
        this.reconnect();
      }
    });

    this.socketTask.onOpen(() => {
      console.log('WebSocket连接已打开');
      // 重置重连尝试次数只有在连接成功时进行
      this.reconnectAttempts = 0;
    });

    this.socketTask.onMessage(async (event) => {
      // 处理接收到的消息
      let data = JSON.parse(event.data);
      let type = data.type || '';
      if(type == 'ping'){
        this.send('pong');
      } else if(type == 'init') {
		let client_id = JSON.parse( event.data).client_id;
		await myRequest({
			url: api.bingUid,
			data: {
				'client_id': client_id
			},
			success: (resp)=>{
				if(resp.data.code == 200){
					uni.showToast({
						title: "ws绑定成功",
						position: "center"
					});
					console.log("ws绑定成功");
				} else {
					uni.showToast({
						title: "ws绑定失败："+resp.data.msg,
						position: "center"
					})
					console.log("ws绑定失败：",resp.data.msg);
				}
			}
		})
        this.eventEmitter.emit('message', data); // 触发 message 事件
      } else {
        console.log('从服务器收到消息:', event.data);
        this.eventEmitter.emit('message', data); // 触发 message 事件
      }
    });

    this.socketTask.onError((error) => {
      console.log('WebSocket错误:', error);
      this.reconnect();
    });

    this.socketTask.onClose((error) => {
      console.log('WebSocket连接关闭:', error);
      this.reconnect();
    });
  }

  reconnect() {
    console.log(`正在重连...`);
    setTimeout(() => {
      this.connect();
    }, this.reconnectInterval);
  }

  send(data) {
    if (this.socketTask && this.socketTask.readyState === 1) { // 1 表示 OPEN
      this.socketTask.send({
        data: data,
        success: () => {
          if(data != 'pong'){
            console.log('消息发送:', data);
          }
        },
        fail: (err) => {
          console.error('发送消息失败:', err);
        }
      });
    } else {
      console.error('WebSocket未打开。当前状态:', this.socketTask ? this.socketTask.readyState : 'null');
    }
  }

  close() {
    this.isClosedByUser = true; // 设置标志位，表示用户主动关闭连接
    if (this.socketTask) {
      this.socketTask.close({
        success: () => {
          console.log('WebSocket已成功关闭');
        },
        fail: (err) => {
          console.error('关闭WebSocket失败:', err);
        }
      });
    }
  }

  on(event, listener) {
    this.eventEmitter.on(event, listener);
  }

  off(event, listener) {
    this.eventEmitter.off(event, listener);
  }
}
